import React, {
	PureComponent
} from 'react'
import { connect } from 'dva'
import router from 'umi/router';
import { Form, Input, Tooltip, Dropdown, Menu, Button } from 'antd'
import { Icon } from 'react-fa'
import Dialog, { withRef } from '@/components/Dialog'
import { SimpeList } from '@/components/Grid'
import Card from '@/components/Card'
import settings, { getPagination } from '@/settings'
import { $request, $http } from '@/utils/request'
import Authorized, { checkRouteAuth } from '@/components/Authorized'

@Form.create()
@connect(({ folder: { data } }) => ({ data }))
@withRef
class ModelForm extends React.Component {
	formLayout = {
		// labelAlign: 'left',
		// labelCol: {
		// 	span: 5
		// },
		// wrapperCol: {
		// 	span: 19
		// },
	};
	componentDidMount() {
		const {
			id,
			dispatch
		} = this.props;

		if (id) {
			dispatch({
				type: 'folder/fetchOne',
				payload: {
					id
				}
			});
		}
	};
	handleSubmit = (_, callback) => {
		const {
			form
		} = this.props

		form.validateFields((err, values) => {
			if (!err) {
				callback(values)
			}
		})
	};
	render() {
		const {
			id,
			data = {},
			form: {
				getFieldDecorator
			}
		} = this.props

		return (
			<Form onSubmit={this.handleSubmit} layout="vertical">
	          <Form.Item label="文件夹名称" {...this.formLayout}>
	            {getFieldDecorator('name', {
					rules: [{
						required: true,
						message: '请输入文件夹名称'
					}, {
						validator: (rule, value, callback) => {
							$http.post('valid/foldername', {
								data: {
									id,
									value
								},
								type: true,
								requestType: 'form'
							}).then(data => {
								data.valid ? callback() : callback("文件夹已存在")
							})
						}
					}],
	              	initialValue: data.name,
	            })(<Input placeholder="请输入" />)}
	          </Form.Item>
	        </Form>
		)
	}
}

@connect(({
	app: {
		user = {}
	},
	folder: {
		list = {},
		params
	},
	loading
}) => ({
	user,
	list,
	params,
	loading: loading.effects['folder/fetchAll'],
}))
@Form.create()
class FolderPage extends PureComponent {
	state = {
		selectedRows: []
	};
	componentDidMount() {
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'folder/fetchAll',
		});
	};
	handleAdd = e => {
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'folder/reset'
		});
		Dialog.open({
			title: '新建文件夹',
			component: ModelForm,
			url: 'folder/add',
			onOk: data => {
				this.handleReload()
			}
		})
	};
	handleEdit(e, id) {
		e.stopPropagation()
		if (id === undefined) {
			const { selectedRows } = this.state;
			id = selectedRows[0].id;
		}
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'folder/reset'
		});
		Dialog.open({
			title: '修改文件夹',
			url: 'folder/update',
			data: {
				id
			},
			options: {
				type: 'put'
			},
			onOk: data => {
				this.handleReload()
			},
			component: props => (<ModelForm {...props} id={id} />),
			connect: ({ loading }) => ({ loading: loading.effects['folder/fetchOne'] })
		})
	};
	handleRemove(e, id) {
		e.stopPropagation()
		const { selectedRows } = this.state;
		Dialog.confirm({
			title: '确认提示',
			content: '确定要删除已选择的文件夹？',
			onOk: () => {
				$request.put('folder/delete', {
					data: {
						ids: selectedRows.map(_ => _.id)
					}
				}).then(data => {
					this.handleReload()
				})
			}
		})
	};
	handleReload = () => {
		const { params, dispatch } = this.props;
		dispatch({
			type: 'folder/fetchAll',
			payload: params
		})
	};
	handleSearch = (value, e) => {
		e.preventDefault();
		const { params, dispatch } = this.props;
		const pagination = getPagination({
			pageNumber: 1
		})
		dispatch({
			type: 'folder/fetchAll',
			payload: {
				...params,
				...pagination,
				name: value
			}
		})
	};
	handleGridChange = (pageNumber, pageSize) => {
		const { params, dispatch } = this.props;
		
		const pagination = getPagination({
			pageSize,
			pageNumber
		})
		const payload = {
			...params,
			...pagination
		}

		dispatch({
			type: 'folder/fetchAll',
			payload,
		})
	}
	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};
	handleMenuEvent(e, key, id) {
		e.stopPropagation()
		switch (key) {
			case 'rename' :
				this.handleEdit(e, id)
				break
			case 'preview' :
				// router.push({
				// 	pathname: '/file',
				// 	query: {
				// 		id: id
				// 	}
				// })
				router.push(`/file/${id}`)
				break
			default :
		}
	}
	render() {
		const { selectedRows } = this.state;
		const {
			user: {
				authorities = []
			},
			params,
			loading,
			list: {
				data,
				total
			}
		} = this.props

		const pageNumber = params[settings.pageNumber]

		const renderMenu = id => (
				  <Menu onClick={({domEvent, key}) => this.handleMenuEvent(domEvent, key, id)}>
				    {checkRouteAuth(authorities)('FOLDER_EDIT') && <Menu.Item key="rename">重命名</Menu.Item>}
				    {checkRouteAuth(authorities)('FILE_VIEW') && <Menu.Item key="preview">查看详情</Menu.Item>}
				  </Menu>
				);
		const getActions = (item) => {
			let actions = []
			if (checkRouteAuth(authorities)('FOLDER_EDIT')) {
				actions = [...actions, <Tooltip title="编辑"><Icon name="edit" onClick={e => this.handleEdit(e, item.id)} /></Tooltip>]
			}
			if (checkRouteAuth(authorities)('FOLDER_DEL')) {
				actions = [...actions, <Icon name="trash-o" onClick={e => this.handleRemove(e, item.id)} />]
			}
			if (checkRouteAuth(authorities)('FOLDER_EDIT', 'FILE_VIEW')) {
				actions = [...actions, <Dropdown overlay={renderMenu(item.id)} trigger={['click']} onClick={e => e.stopPropagation()}><Icon name="ellipsis-h" /></Dropdown>]
			}
			return actions
		}
		return (
			<div className="wrap">
				<div className="x-panel">
					<div className="x-toolbar">
						<div className="fl">
							<Button.Group>
								<Authorized authorities={authorities} authority="FOLDER_ADD"><Button type="primary" onClick={this.handleAdd}>新建</Button></Authorized>
								<Authorized authorities={authorities} authority="FOLDER_EDIT"><Button onClick={e => this.handleEdit(e)} disabled={selectedRows.length !== 1}>编辑</Button></Authorized>
								<Authorized authorities={authorities} authority="FOLDER_DEL"><Button type="danger" disabled={selectedRows.length === 0} onClick={e => this.handleRemove(e)}>删除</Button></Authorized>
							</Button.Group>
						</div>
						<div className="fr x-query">
							<Form layout="inline">
								<Input.Search placeholder="请输入要查询的关键词" onSearch={this.handleSearch} />
							</Form>
						</div>
					</div>
					<div className="x-container">
						<SimpeList 
							grid={{
								gutter: 12,
								xs: 1,
								sm: 2,
								md: 2, 
								lg: 4,
								xl: 6,
								xxl: 6
							}}
							data={data}
							renderItem={
								item => (
									<SimpeList.Item 
										actions={getActions(item)}>
										<Card 
											data={{
												icon: 'folder-open',
												name: item.name
											}}
											actions={[{
												icon: 'edit'
											}, {
												icon: 'ellipsis'
											}]} />
									</SimpeList.Item>
								)
							}
							selectedRows={selectedRows} 
							onSelectRow={this.handleSelectRows} 
							loading={loading}
							pagination={{
								pageNumber,
								total
							}}
							onChange={this.handleGridChange}
						/>
					</div>
				</div>
			</div>
		)
	}
}

export default FolderPage